package com.geek.mq.rabbitmq.util;

import com.geek.mq.rabbitmq.constant.RabbitConstant;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.net.URISyntaxException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.TimeoutException;

public class RabbitMqUtil {

	private volatile static Connection connection;
	private static final ConnectionFactory connectionFactory = new ConnectionFactory();

	public static Connection getConnection() throws IOException, TimeoutException {
		if(connection == null){
			synchronized (RabbitMqUtil.class){
				if(connection == null){
					connectionFactory.setUsername(RabbitConstant.RABBITMQ_USERNAME);
					connectionFactory.setPassword(RabbitConstant.RABBITMQ_PASSWORD);
//					connectionFactory.setVirtualHost("/test");
					connectionFactory.setHost(RabbitConstant.RABBITMQ_URL);
					connectionFactory.setPort(RabbitConstant.RABBITMQ_PORT);
					connection = connectionFactory.newConnection();
				}
			}
		}else if(!connection.isOpen()){
			connection = connectionFactory.newConnection();
		}
		return connection;
	}

}
